package com.yihu.cms.action;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.yihu.article.beans.Attachment;
import com.yihu.article.beans.AttachmentQueryVO;
import com.yihu.article.beans.EditorManagerPage;
import com.yihu.beans.PictureDetail;
import com.yihu.beans.fileManager.Files;
import com.yihu.beans.fileManager.FmListConditions;
import com.yihu.cms.service.ArticleService;
import com.yihu.cms.service.FileManagerService;
import com.yihu.cms.util.CMSConstants;
import com.yihu.cms.util.CommonUtils;
import com.yihu.cms.util.FormatDateTime;
import com.yihu.cms.util.InfoHelp;
import com.yihu.cms.util.PropertiesUtil;

@Controller
public class RichFileManagerController extends BaseController {
	private final Logger logger = LoggerFactory.getLogger(RichFileManagerController.class); 
	private ArticleService as = new ArticleService();
	FileManagerService fs = new FileManagerService();
	@Autowired
	private HttpServletRequest request;
	
	// 如果是用户上传 USERID的值传到ParentFolder。
	@RequestMapping(value = "/richText/upload", method = RequestMethod.POST)
	public @ResponseBody Object upload(@RequestBody Attachment a) {
		Files file = new Files();
		String type = a.getFiletype();
		file.setParentFolder(a.getParentFolder());
		if(InfoHelp.isBlank(a.getParentFolder())){
			String folder = getFolder(type)+FormatDateTime.toShortTimeString2(new Date());
		    file.setParentFolder(folder);
		}
		if(StringUtils.isNotBlank(type)){
			file.setFileType(type);
		}else{
			file.setFileType("folder");
		}
		file.setFileName(a.getFilename());
//		file.setDirectory(true);
		file.setCreateTime(new Date());
		PictureDetail picture = new PictureDetail();
		picture.setId(a.getFileid());
		file.setPicture(picture);
		file.setRichFile(true);
		int result = fs.create( file );
		log.info("result=" + result);
		return getResult(result, null);
	}
	//path  = /richFile/image/20161013 exmp
	//如果查询用户的图片空间，path=123
	@RequestMapping(value="/editor/filemanager", method = RequestMethod.GET)
	public @ResponseBody Object richtextManager(AttachmentQueryVO vo) {
		String type = vo.getDir();
		logger.debug("fileManager.type："+type);
		
		
		log.info("filemanger list .");
		FmListConditions fmlc = new FmListConditions();
		List<Files> files = new ArrayList<Files>();
		String order = vo.getOrder();
		/*if(InfoHelp.isBlank(vo.getPath())){
			vo.setPath("/richFile");
		}*/
		String path = vo.getPath();
		if(order!=null && !"".equals(order))
		{
			if("name".equalsIgnoreCase(order))
				fmlc.setOrder("fileName");
			else if("time".equalsIgnoreCase(order))
				fmlc.setOrder("createTime");
			else if("size".equalsIgnoreCase(order))
				fmlc.setOrder("fileSize");
			else
			{
				log.info("unknown order . order=" + order);
				return getResult(1 , files);
			}
		}
		
		
		if(StringUtils.isNotBlank(path)){
			fmlc.setParentFolder(path);
		}
		
		if(StringUtils.isNotBlank(type)){
			//fmlc.setType(type);
		}
		files = fs.getList(fmlc);
		FMListreponse fmr = new FMListreponse();
		fmr.setFiles(files);
		fmr.setPath(path);
		fmr.setTotalCount(files.size());
		//转换为富文本结构  
		//String current_url,String current_dir_path,
		//String moveup_dir_path,long total_count
		EditorManagerPage resultPage = new EditorManagerPage("","","",files.size());
		List<Attachment> attas = new ArrayList<Attachment>();
		
		for(Files f:files){
			/*Date d = a.getDatetime();
			FormatDateTime.toShortTimeString(d);*/
			Attachment a = new Attachment();
			a.setParentFolder(f.getParentFolder());
			a.setFilename(f.getFileName());
			a.setFilesize(f.getSize());
			a.setFiletype(f.getFileType());
			a.setFolder(f.getFileName());
			
			if(f.getFileType().equals("folder")){
				a.setUrl(a.getParentFolder()+"/"+a.getFolder());
				a.setFilename(a.getFolder());
				a.setIs_dir(true);
				a.setHas_file(true);
			}
			else{
				a.setIs_photo(true);
				a.setFileid(f.getPicture().getId());
				a.setUrl(getnerateUrl(a.getFileid(), a.getFiletype()));
			}
			
			attas.add(a);
		}
		resultPage.setFile_list(attas);
		resultPage.setCurrent_dir_path(path);
		resultPage.setMoveup_dir_path(this.getMoveUpPath(path));
		//String json = JSON.toJSONString(resultPage);
		//logger.debug("richtextManager.json："+json);
		return resultPage;
	}

	private String getFolder(String type) {
		String folder = "";
		if(CMSConstants.EDITOR_IMAGE.equals(type)){
			folder = PropertiesUtil.getInstance().getProperty("articleimagedir");
		}
		else if(CMSConstants.EDITOR_FLASH.equals(type)){
			folder = PropertiesUtil.getInstance().getProperty("articleflashdir");
		}
		else if(CMSConstants.EDITOR_media.equals(type)){
			folder = PropertiesUtil.getInstance().getProperty("articlemediadir");
		}
		else if(CMSConstants.EDITOR_File.equals(type)){
			folder = PropertiesUtil.getInstance().getProperty("articlefiledir");
		}
		else{
			return "dir error";
		}
		return folder;
	}

	
	
	@RequestMapping(value = "/richtextManager/delete/{ids}", method = RequestMethod.DELETE)
	public @ResponseBody Object deleteRichText(@PathVariable("ids") String ids) {
		int result = as.deleteAttachment(ids);
		return CommonUtils.getResult(result, null);
	}
	
	
	private String getnerateUrl(String fileId, String fileType) {
		String serverIpAdress = PropertiesUtil.getInstance().getProperty("serverurl");
		String url = serverIpAdress + "/ps/download/"+fileId+"?type="+fileType;
		return url;
	}
	
	private class FMListreponse{
		List<Files> files = null;
		String path = "";
		int totalCount = 0;
		
		public List<Files> getFiles() {
			return files;
		}
		public void setFiles(List<Files> files) {
			this.files = files;
		}
		public String getPath() {
			return path;
		}
		public void setPath(String path) {
			this.path = path;
		}
		public int getTotalCount() {
			return totalCount;
		}
		public void setTotalCount(int totalCount) {
			this.totalCount = totalCount;
		}
	}
	
	private  String getMoveUpPath(String path) {
		String paths[] = path.split("/");
		StringBuffer moveUpPath = new StringBuffer();
		if(paths!=null&&paths.length>0){
			for(int i=1;i<paths.length-1;i++){
				moveUpPath.append("/").append(paths[i]);
			}
		}
		return moveUpPath.toString();
	}
}
